package devcken.datatables.serverside;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import devcken.hibernate.query.OrderBy;
import devcken.utility.Pair;

public class SortQuery
{
	public static List<Pair<String, OrderBy>> getSortConditions(HttpServletRequest request, int sortColumnCount) throws ServletRequestBindingException
	{
		List<Pair<String, OrderBy>> sortConditions = new ArrayList<Pair<String, OrderBy>>();
		
		for (int index = 0; index < sortColumnCount; index++)
		{
			int sortingColumnIndex = ServletRequestUtils.getIntParameter(request, String.format("iSortCol_%d", index), -1); 
			
			if (sortingColumnIndex > -1 &&
					ServletRequestUtils.getBooleanParameter(request, String.format("bSortable_%d", sortingColumnIndex), false))
			{
				String dataName = ServletRequestUtils.getStringParameter(request, String.format("mDataProp_%d", sortingColumnIndex));
				
				String sortingDirection = ServletRequestUtils.getStringParameter(request, String.format("sSortDir_%d", index));
				
				OrderBy orderBy = OrderBy.parse(sortingDirection);
				
				sortConditions.add(new Pair<String, OrderBy>(dataName, orderBy));
			}
		}
		return sortConditions;
	}
}